﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ERPMVC.Models;
using System.Xml;
using System.Globalization;

namespace ERPMVC.Controllers
{
    public class ContasaPagarController : Controller
    {
        //
        // GET: /ContasaPagar/

        private ContasDBEntities _db = new ContasDBEntities();

        public ActionResult Index()
        {
            //return View();
            return View(_db.contasapagar.ToList());
        }


       
        //
        // GET: /ContasaPagar/Details/5

        public ActionResult Details(int id)
        {
            var conta = _db.contasapagar.First(x => x.ContaID == id);
            if (conta == null)
                return View("NotFound");

            return View(conta);
        }

        //
        // GET: /ContasaPagar/Create

        public ActionResult Create()
        {
        //{
        //    Page page = iPageData.SelectPageById(id);

        //    ViewData["PageCreatedByUserId"] = UserList();
        //    ViewData["PageParentId"] = new SelectList(iPageData
        //                                          .SelectTopLevelMenuItems(),
        //                                          "PageId", "PageTitle", page.PageParentId);

        //    ViewData.Model = page;

            return View();
        } 

        //
        // POST: /ContasaPagar/Create

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult Create([Bind(Exclude = "Id")] contasapagar contaCriada)
        {

            if (!ModelState.IsValid)
                return View();
            _db.AddTocontasapagar(contaCriada);
            _db.SaveChanges();
            
            return RedirectToAction("Index");

        } 


        //
        // HTTP GET: /Customers/Delete/1

        [Authorize]
        public ActionResult Delete(int id)
        {
           
            var conta = _db.contasapagar.First(x => x.ContaID == id);
            if (conta == null)
                return View("NotFound");

            return View(conta);
        }

        // 
        // HTTP POST: /Customers/Delete/1

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id, string confirmButton)
        {
            
            var conta = _db.contasapagar.First(x => x.ContaID == id);
            if (conta == null)
                return View("NotFound");

            _db.DeleteObject(conta);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        //
        // GET: /ContasaPagar/Edit/5
 
        public ActionResult Edit(int id)
        {

            var contaEditar = (from m in _db.contasapagar

                               where m.ContaID == id

                               select m).First();
            return View(contaEditar);
        }

        //
        // POST: /ContasaPagar/Edit/5

        // POST: /Home/Edit/5 

        [AcceptVerbs(HttpVerbs.Post)]

        public ActionResult Edit(contasapagar contaToEdit)
        {

            var originalConta = (from m in _db.contasapagar

                                 where m.ContaID == contaToEdit.ContaID

                                 select m).First();

            if (!ModelState.IsValid)

                return View(originalConta);

            _db.ApplyPropertyChanges(originalConta.EntityKey.EntitySetName, contaToEdit);

            _db.SaveChanges();

            return RedirectToAction("Index");

        }

        public ActionResult PagarSalarios()
        {
            ContasDBEntities _db = new ContasDBEntities();


            List<FinanceiroServices.Financeiro.employee> empregados = new List<FinanceiroServices.Financeiro.employee>();
            int funcionarios = 0;

            XmlDocument xml = new XmlDocument();

            xml.Load("http://rhlabsoft.heroku.com/employees.xml");


            //Verificando se nesse mes já foi pago
            var pago = (from m in _db.contasapagar

                        where m.vencimento.Month >= DateTime.Now.Month

                        select m);



            if (pago.ToList().Count == 0)
            {
                foreach (XmlNode item in xml.LastChild.ChildNodes)
                {
                    funcionarios++;
                    float TotalAmount = 0;
                    FinanceiroServices.Financeiro.employee a = new FinanceiroServices.Financeiro.employee();
                    foreach (XmlNode employ in item.ChildNodes)
                    {


                        if (employ.Name.Contains("name") && !employ.Name.Contains("role-name"))
                        {
                            a.name = employ.InnerText;
                        }
                        if (employ.Name.Contains("id"))
                        {
                            a.id = Int32.Parse(employ.InnerText, CultureInfo.InvariantCulture);
                        }
                        if (employ.Name.Contains("bank-account-number"))
                        {
                            a.account = Int32.Parse(employ.InnerText, CultureInfo.InvariantCulture);
                        }

                        // TotalAmount = 0;
                        if (employ.Name.Contains("salary"))
                        {
                            a.rendimento += float.Parse(employ.InnerText, CultureInfo.InvariantCulture);

                        }
                        if (employ.Name.Contains("benefits"))
                        {
                            foreach (XmlNode benefits in employ.ChildNodes)
                            {
                                foreach (XmlNode benefit in benefits)
                                {
                                    if (benefit.Name.Contains("value"))
                                    {
                                        a.rendimento += float.Parse(benefit.InnerText, CultureInfo.InvariantCulture);
                                    }
                                }

                            }
                        }


                    }
                    //a.rendimento = TotalAmount;
                    empregados.Add(a);

                    //Adicionando ao contas a pagar no pago
                    //ContaBancaria bb = new ContaBancaria();
                    //bb.Agencia = 1;
                    //bb.Banco = 1;
                    //bb.ContaCorrente = a.account;
                    //_db.AddToContaBancaria(bb);
                    //_db.SaveChanges();

                    contasapagar pagar = new contasapagar();

                    //pagar.ContaBancaria = bb;
                    pagar.descricao = "Salário referente ao mês " + DateTime.Now.Month.ToString();

                    pagar.titulo = (decimal)a.rendimento;
                    pagar.documento = "Salário";
                    pagar.favorecido = a.name;
                    pagar.juros = (double)(0);
                    pagar.multa = (decimal)(0);
                    pagar.Pago = true;
                    pagar.vencimento = DateTime.Now;

                    _db.AddTocontasapagar(pagar);
                    _db.SaveChanges();

                }
            }
            return RedirectToAction("Index");
        }
    }
}
